<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>滚动触发帧动画</title>
  <style>
    body {
      height: 3000px; /* 给页面足够滚动空间 */
      margin: 0;
      display: flex;
      justify-content: center;
      align-items: start;
      padding-top: 100px;
      background: #111;
    }
    #animation-container {
      position: fixed; /* 固定位置，跟随滚动 */
      top: 50px;
      left: 50%;
      transform: translateX(-50%); /* 居中 */
      width: 600px;
      height: 400px;
      background: #222;
      display: flex;  
      justify-content: center;  /* 居中 */
      align-items: center;  /* 居中 */
    }
    #frame {
      max-width: 100%;
      max-height: 100%;
      user-select: none; /* 禁止用户选择 */
      pointer-events: none; /* 禁止用户点击 */
    }
  </style>
</head>
<body>

<div id="animation-container">
  <img id="frame" src="https://www.apple.com/105/media/us/airpods-3rd-generation/2021/3c0b27aa-a5fe-4365-a9ae-83c28d10fa21/anim/battery/large/0001.jpg" alt="动画帧" />
</div>

<script>
  const totalFrames = 60; // 总帧数
 const framePath = (index) => 
  `https://www.apple.com/105/media/us/airpods-3rd-generation/2021/3c0b27aa-a5fe-4365-a9ae-83c28d10fa21/anim/battery/large/${String(index).padStart(4, '0')}.jpg`;

  const frameImg = document.getElementById('frame');

  // 预加载图片（可选，提高体验）
  const preloadFrames = () => {
    for (let i = 1; i <= totalFrames; i++) {
      const img = new Image();
      img.src = framePath(i);
    }
  };
  preloadFrames();

  // 映射滚动距离到帧数，假设滚动3000px映射到60帧
  const scrollRange = 3000;

  window.addEventListener('scroll', () => {
    // 当前滚动距离
    const scrollTop = window.scrollY;

    // 计算帧索引
    let frameIndex = Math.floor((scrollTop / scrollRange) * totalFrames);
    if (frameIndex < 1) frameIndex = 1;
    if (frameIndex > totalFrames) frameIndex = totalFrames;

    // 切换图片
    const newSrc = framePath(frameIndex);
    if (frameImg.src !== newSrc) {
      frameImg.src = newSrc;
    }
  });
</script>

</body>
</html>
